import time

from model.HourseInfo import HourseInfo
from utils import createWordCloud
from utils.getPublicData import getAllHourseInfoMap, cityLists


def getHomeGeoCharData(hourseData):
    prices = averagePrice(hourseData)
    print(prices)
    data = {}
    for k, v in prices.items():
        # '保定市': 8545.2
        # print(k, v)
        for province in cityLists:
            for c in province['citys']:
                if k.find(c) != -1:
                    data[province['province']] = v
    # print(data)

    result = []
    for k, v in data.items():
        result.append({'name': k, 'value': v})
    return result


def averagePrice(hourseData):
    cityPrices = {}     # 城市每平单价总和
    cityCounts = {}     # 城市出现次数
    for hourse in hourseData:
        city = hourse.city
        # bug: 1.1元/平
        price = int(float(hourse.price))
        if city in cityPrices:
            cityPrices[city] += price
            cityCounts[city] += 1
        else:
            cityPrices[city] = price
            cityCounts[city] = 1

    averagePrices = {}  # 城市每平均价
    for city in cityPrices:
        averagePrices[city] = round(cityPrices[city] / cityCounts[city], 1)

    return averagePrices


def getHomeTagsData(hourseData):
    title = ''
    total = len(hourseData)
    maxPrice = 0

    hourseTypes = {}
    saleStatus = {}
    for i in hourseData:
        title += i.title
        if int(float(i.price)) > maxPrice:
            maxPrice = int(float(i.price))

        if hourseTypes.get(i.hourse_type, -1) == -1:
            hourseTypes[i.hourse_type] = 1
        else:
            hourseTypes[i.hourse_type] += 1

        if saleStatus.get(i.sale_status, -1) == -1:
            saleStatus[i.sale_status] = 1
        else:
            saleStatus[i.sale_status] += 1

    mostHourseType = list(sorted(hourseTypes.items(), key=lambda x: x[1], reverse=True))[0][0]

    status = list(sorted(saleStatus.items(), key=lambda x: x[1], reverse=True))[0][0]
    if status == '1':
        status = '在售'
    elif status == '2':
        status = '已售'
    elif status == '3':
        status = '出租中'
    elif status == '4':
        status = '已出租'
    elif status == '5':
        status = '预售'
    else:
        status = '其他'

    return total, maxPrice, mostHourseType, status, title


def getHomeRadarData(hourseData):
    start = time.time()
    data = {}
    for h in hourseData:
        found = False
        for province in cityLists:
            if found:
                # 找到就退出, 避免不必要的遍历造成耗时
                break
            for c in province['citys']:
                if h.city.find(c) == -1:
                    continue
                if data.get(province['province'], -1) == -1:
                    data[province['province']] = 1
                else:
                    data[province['province']] += 1
                found = True
                break

    maxNum = max(data.values())
    resultIndicator = []
    resultNum = []
    for k, v in data.items():
        resultIndicator.append({
            'text': k.replace('省', '').replace('自治区', '').replace('壮族', '').replace('回族', '').replace('维吾尔', ''),
            'max': maxNum
        })
        resultNum.append(v)
    print(time.time()-start)
    return resultIndicator, resultNum


def ceshi(text):
    # createWordCloud.run(text, 'title.png')
    print(text)
    pass


def getSearchHourseDataByTitle(keyword, hourseData):
    hourseList = []
    for h in hourseData:
        if h.title.find(keyword) != -1:
            hourseList.append(h)

    return hourseList

def getSearchHourseDataByTitle2(keyword):
    hourseData = HourseInfo.query.filter(HourseInfo.title.like('%{}%'.format(keyword))).all()
    return hourseData


def getHoursePriceCharCitysList(hourseData):
    citys = list(set([x.city for x in hourseData]))
    return citys


def getCityBarChartData(hourseData):
    cloumn = ['<=4000', '4000-6000', '6000-8000', '8000-10000', '10000-12000', '12000-15000', '15000-18000', '>=18000']

    priceData = [0 for i in range(len(cloumn))]
    for h in hourseData:
        price = int(h.price)
        if price <= 4000:
            priceData[0] += 1
        elif price < 6000:
            priceData[1] += 1
        elif price < 8000:
            priceData[2] += 1
        elif price < 10000:
            priceData[3] += 1
        elif price < 12000:
            priceData[4] += 1
        elif price < 15000:
            priceData[5] += 1
        elif price < 18000:
            priceData[6] += 1
        else:
            priceData[7] += 1

    return cloumn, priceData


def getOpenDateLineChartData(hourseData):
    # X-开盘时间
    # Y-楼盘均价
    counts = {}
    openDatePriceDict = {}  # '2019-04-15': [5300, 5500]
    for h in hourseData:
        if h.open_date.strip() == '':
            continue

        if openDatePriceDict.get(h.open_date):
            counts[h.open_date] += 1
            openDatePriceDict[h.open_date] += int(h.price)
        else:
            counts[h.open_date] = 1
            openDatePriceDict[h.open_date] = int(h.price)
    openDateSort = sorted(openDatePriceDict.items(), key=lambda x:x[0])

    print(counts)
    print(openDateSort)

    cloumn = []
    data = []
    for k, v in openDateSort:
        if v == 0:
            continue
        cloumn.append(k)
        data.append(round(v / counts.get(k), 2))

    return cloumn, data


def getTotalPriceChartData(hourseData):
    data = []
    for h in hourseData:
        data.append(h.total_price_range)

    return data



def getHourseDetailChartData(hourseData):
    roomDist = {}
    for h in hourseData:
        for room in h.rooms_desc:
            if roomDist.get(room):
                roomDist[room] += 1
            else:
                roomDist[room] = 1

    result = []
    for k, v in roomDist.items():
        result.append({
            'name': k,
            'value': v
        })
    return result


def getHourseAreaChartData(hourseData, rangeType):
    if rangeType == 'small':
        xData = [
            '0-40',
            '40-60',
            '60-80',
            '80-100',
            '100-120',
            '120-150',
            '150-n',
        ]
        yData = [0 for i in range(len(xData))]
        for h in hourseData:
            areaRange = h.area_range
            print(f'-------- {areaRange}')
            if areaRange[0] == '':
                continue
            if len(areaRange) == 1 and areaRange[0].find('-') != -1:
                areaRange = int(areaRange[0].split('-')[0])
            else:
                areaRange = int(areaRange[0])
            if areaRange < 40:
                yData[0] += 1
            elif areaRange < 60:
                yData[1] += 1
            elif areaRange < 80:
                yData[2] += 1
            elif areaRange < 100:
                yData[3] += 1
            elif areaRange < 120:
                yData[4] += 1
            elif areaRange < 150:
                yData[5] += 1
            else:
                yData[6] += 1
    elif rangeType == 'big':
        xData = [
            '80-100',
            '100-110',
            '110-120',
            '120-130',
            '130-140',
            '140-160',
            '160-n',
        ]
        yData = [0 for i in range(len(xData))]
        for h in hourseData:
            areaRange = h.area_range[1]
            if len(areaRange) == 1 and areaRange[0].find('-') != -1:
                areaRange = int(areaRange[0].split('-')[1])
            else:
                areaRange = int(areaRange[1])
            if areaRange < 100:
                yData[0] += 1
            elif areaRange < 110:
                yData[1] += 1
            elif areaRange < 120:
                yData[2] += 1
            elif areaRange < 130:
                yData[3] += 1
            elif areaRange < 140:
                yData[4] += 1
            elif areaRange < 160:
                yData[5] += 1
            else:
                yData[6] += 1
    else:
        xData = []
        yData = []

    return xData, yData


def getHourseDecorationChartData(hourseData):
    data = {}
    for h in hourseData:
        if h.hourse_decoration == '':
            continue
        if data.get(h.hourse_decoration):
            data[h.hourse_decoration] += 1
        else:
            data[h.hourse_decoration] = 1

    result = []
    for k, v in data.items():
        result.append({'name': k, 'value': v})
    return result


def getHourseTypeChartData(hourseData):
    data = {}
    for h in hourseData:
        if h.hourse_type == '':
            continue
        if data.get(h.hourse_type):
            data[h.hourse_type] += 1
        else:
            data[h.hourse_type] = 1

    result = []
    for k, v in data.items():
        result.append({'name': k, 'value': v})
    return result




